/**
 * author: redd
 * create_time: 2017/12/26 17:09
 * description:
 */
 


import React, {Component} from 'react'
import PropTypes from 'prop-types'

const buttonStyle = {
  margin: '10px'
}

export default class Counter extends Component {
  constructor(props) {
    super(props)
    this.state = {
      count: props.initValue
    }

    this.onClickIncrementButton = this.onClickIncrementButton.bind(this)
    this.onClickDecrementButton = this.onClickDecrementButton.bind(this)
  }

  componentWillMount() {
    console.log('enter componentWillMount ' + this.props.caption)
  }

  componentDidMount() {
    console.log('enter componentDidMount ' + this.props.caption)
  }

  componentWillReceiveProps(nextProps) {
    console.log('enter componentWillReceiveProps ' + this.props.caption)
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('enter shouldComponentUpdate ' + this.props.caption)
    return (nextProps.caption !== this.props.caption) || (nextState.count !== this.state.count)
  }

  onClickIncrementButton() {
    this.setState({
      count: this.state.count + 1
    })
  }

  onClickDecrementButton() {
    this.setState({
      count: this.state.count - 1
    })
  }


  render() {
    console.log('enter render ' + this.props.caption)
    const {caption} = this.props
    return (
      <div>
        <button style={buttonStyle} onClick={this.onClickDecrementButton}>-</button>
        <button style={buttonStyle} onClick={this.onClickIncrementButton}>+</button>
        <span>{caption} count: {this.state.count}</span>
      </div>
    )
  }
}



Counter.propTypes = {
  caption: PropTypes.string.isRequired,
  initValue: PropTypes.number
}


Counter.defaultProps = {
  initValue: 0
}